package com.h2cloud.JUCTest.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

import static com.h2cloud.JUCTest.TimeUtil.Sleeper.sleep;

/**
 * @Package: com.h2cloud.JUCTest.cas
 * @ClassName: TestABA
 * @Author: h2cloud
 * @CreateTime: 2022/5/30 4:42 下午
 * @Description:
 */
@Slf4j
public class TestABA {
	static AtomicReference<String> ref = new AtomicReference<>("A");

	public static void main(String[] args) throws InterruptedException {
		log.debug("main start...");
		// 获取值 A
		// 这个共享变量被它线程修改
		String prev = ref.get();
		other();
		sleep(1);
		// 尝试改为 C
		log.debug("change A->C {}", ref.compareAndSet(prev, "C"));
	}

	private static void other() {
		new Thread(() -> {
			log.debug("change A->B {}", ref.compareAndSet(ref.get(), "B"));
		}, "t1").start();
		sleep(1);
		new Thread(() -> {
			log.debug("change B->A {}", ref.compareAndSet(ref.get(), "A"));
		}, "t2").start();
	}
}
